#coding=utf-8

import argparse,json,os
from xiapibuy import Xiapibuy
from pysqlite import sqliteDB
from pathlib import Path
import time

BASE_DIR = Path(os.path.realpath(__file__)).parents[2]
db_path = os.path.join(BASE_DIR,"app","downdb.db")
db = sqliteDB(db_path)




def get_token_from_db(str_app_key):
    res =  db.findall("spider_user_control","user_appkey='{}'".format(str_app_key))
    #print(res)
    if len(res) ==1:
        return res[0][6]
    return ""
        
'''
每隔60*30 时间执行一次
使用已经插入的cookie进行关注，对每个店铺选中进行一次关注

'''
def main_loop():
    time_day = time.strftime("%Y-%m-%d", time.localtime(time.time()))
    xp = Xiapibuy()
    while True:
        time.sleep(60*30)
        #time.sleep(2)
        time_now = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        #跨日后
        print(time_now,time_day)
        if time_now != time_day:
            #重置关注数量
            res =  db.findall("spider_worker_list","")
            for item in res:
                db.update("UPDATE spider_worker_list SET user_today_work_num = 0 WHERE id = {}".format(item[0]))
            
        else:
            #关注cat
            res =  db.findall("spider_worker_list","")
            for item in res:
                # 是以||分隔
                print("**",item)
                if item[7] > 0 and item[8] <450:
                    list_work = []
                    list_work.extend(item[4].split("||"))  # || 
                    list_work.extend(item[5].split("||"))
                    list_work.extend(item[6].split("||"))
                    list_work = [x for x in list_work if x != '']
                    #print(list_work)
                    str_cookie = get_token_from_db(item[1])
                    xp.xiapi_set_cookie(str_cookie)
                    json_ret = {}
                    num_now = item[8]
                    for url in list_work:
                        json_ret = xp.xiapi_saleitem_get_follower(url)
                        if json_ret.get('status',-1) > 0:
                            num_now = num_now + json_ret['data']
                            db.update("UPDATE spider_worker_list SET user_today_work_num = {} WHERE id = {}".format(num_now,item[0]))
                #处理自动关注分类功能
                if item[3]=='enable':
                    item_cat = item[2]
                    str_cookie = get_token_from_db(item[1])
                    xp.xiapi_set_cookie(str_cookie)
                    json_ret = {}
                    json_ret = xp.xiapi_main_run_get_follower(item_cat)
                    num_now = item[8]
                    if json_ret.get('status',-1) > 0:
                        num_now = num_now + json_ret['data']
                        db.update("UPDATE spider_worker_list SET user_today_work_num = {} WHERE id = {}".format(num_now,item[0]))
            time_day = time_now
        



if __name__ == '__main__':
    main_loop()
    # parser = argparse.ArgumentParser(description=
    #         "xiapi web spider")
    # parser.add_argument("-cf", "--cat_follow",type=int,
    #         help="category follow")
    # parser.add_argument("-urlf", "--url_follow",
    #         help="url follow")
    # parser.add_argument("-uf", "--un_follow",
    #         help="unfollow")
    # parser_main(parser.parse_args())
            